package com.hospital.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hospital.dao.PictureDao;
import com.hospital.pojo.Picture;
import com.hospital.service.PictureService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.List;

@Service
public class PictureServiceImpl extends ServiceImpl<PictureDao, Picture> implements PictureService {

    @Resource
    PictureDao pictureDao;
    @Override
    public boolean saveBatchPic(Long pId, String[] pictures) {
        List<Picture> list = new ArrayList<>();
        for (int i = 0; i < pictures.length; i++){
            String str = pictures[i].substring(0,pictures[i].indexOf(","));
            Picture picture = new Picture();
            picture.setImage("/files/images/"+pictures[i].substring(str.length()+1,pictures[i].indexOf(";")));
            picture.setImageNum(Integer.valueOf(pictures[i].substring(pictures[i].indexOf(";")+1)));
            picture.setImageName(str);
            picture.setPId(pId);
            list.add(picture);
        }
        return this.saveBatch(list);
    }

    @Override
    public List<Picture> getPicturePathList(Integer pId) {
        return pictureDao.selectList(Wrappers.<Picture>lambdaQuery().eq(Picture::getPId,pId));
    }

    @Override
    public void deletePictureByPId(Long pId, String[] deleteImages) {
        for (int i = 0; i < deleteImages.length; i++){
            pictureDao.delete(Wrappers.<Picture>lambdaQuery().eq(Picture::getImage,deleteImages[i]));
        }
    }

    @Override
    public void deleteByPId(Integer id) {
        List<Picture> list = pictureDao.selectList(Wrappers.<Picture>lambdaQuery().select(Picture::getImage).eq(Picture::getPId, id));
        for (Picture picture : list) {
            String filePath = System.getProperty("user.dir") + picture.getImage();
            File file = new File(filePath);
            //判断文件是否存在
            if (file.exists()) {
                boolean flag = false;
                flag = file.delete();
                if (flag) {
                    System.out.println("成功删除图片" + file.getName());
                } else {
                    System.out.println("删除失败");
                }
            }
        }
        pictureDao.delete((Wrappers.<Picture>lambdaQuery().eq(Picture::getPId,id)));
    }
}
